<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/7
 * Time: 15:25
 */
require_once DXW_MONGO_DIR."mongodb.php";
class MongoHelper {
    private $_cfg =array();
    public function __construct(){
        $this->_cfg["username"] = DXW_MONGO_USER_NAME;
        $this->_cfg["password"] = DXW_MONGO_USER_PWD;
        $this->_cfg["host"] = DXW_MONGO_HOST;
        $this->_cfg["database"] = DXW_MONGO_DATABASE;
        $this->_cfg["auth_type"] = DXW_MONGO_AUTHMECHANISM;
    }


    static $instance =null;
    public static function create(){
        if(null===self::$instance){
            self::$instance = new self;
        }
        return self::$instance;
    }

    //返回链接实例
    public  function getCollection($col){
        $_connStr = "mongodb://".$this->_cfg["username"].":".$this->_cfg["password"]."@".$this->_cfg["host"]."/".$this->_cfg["database"]."?authMechanism=".$this->_cfg["auth_type"];
        $_man = new \MongoDB\Driver\Manager($_connStr);
        $collection = new \MongoDB\Collection($_man, $this->_cfg["database"], $col);
        return $collection;
    }

    public function find($col,$data=array(),$option=array()){
        $res =  $this->getCollection($col)->find($data,$option)->toArray();
        return $res;
    }
    public function findOne($col,$data=array(),$option=array()){
        $option["limit"] =1;
        $res =  $this->getCollection($col)->find($data,$option)->toArray();
        return $res;
    }
    //模糊查询
    public function like_q($col,$data = array(),$option=array()){
        $filter = array();
        foreach($data as $k=>$v){
            $filter[$k] = array('$regex'=>new \MongoDB\BSON\Regex($v,'i'));
        }
        $res =  $this->getCollection($col)->find($filter,$option)->toArray();
        return $res;
    }

    public function count($col,$data,$option=array()){
        $res =  $this->getCollection($col)->count($data);
        return isset($res) ? $res :0;
    }
}